package com.stendahls.groupbot;

import java.util.Collection;
import java.util.Map;
import java.util.HashMap;
import java.util.logging.Logger;

/**
 *
 */
public class CommandFactory {
    private static final Logger log = Logger.getLogger(CommandFactory.class.getName());


    public static final String COMMAND_PREFIX = "#";

    private static Map<String,Class> availableCommands = new HashMap<String,Class>();

    static {
        availableCommands.put("help", HelpCommand.class);
        availableCommands.put("list", ListGroupCommand.class);
        availableCommands.put("addall", AddAllCommand.class);
    }


    public static boolean isCommand(String candidate) {
        return (candidate != null && candidate.startsWith(COMMAND_PREFIX));
    }

    public static Command find(String command) {

        String strippedCommand = stripCommand(command);

        Class clazz = availableCommands.get(strippedCommand);

        if(clazz != null) {
            try {
                return (Command) clazz.newInstance();
            } catch (InstantiationException e) {
                log.severe(e.getMessage());
                return null;
            } catch (IllegalAccessException e) {
                log.severe(e.getMessage());
                return null;
            }
        }

        return null;
    }

    private static String stripCommand(String command) {
        if(command != null && command.length() > COMMAND_PREFIX.length()) {
            return command.substring(COMMAND_PREFIX.length(), command.length());           
        }
        return command;
    }

    public static Collection<String> getAvailableCommands() {
        return availableCommands.keySet();
    }

}
